package com.wcfsy.wechat.wx.controller;

import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.httpclient.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wcfsy.wechat.wx.entity.ChangeRecordInfo;
import com.wcfsy.wechat.wx.pagination.IPage;
import com.wcfsy.wechat.wx.service.IChangeRecordService;
import com.wcfsy.wechat.wx.util.DateStyle;
import com.wcfsy.wechat.wx.util.StringUtil;
import com.wcfsy.wechat.wx.util.excel.ExcelUtil;
import com.wcfsy.wechat.wx.util.excel.ExcelView;

/**
 * 兑换记录管理
 * 
 * @author yiqiang
 */
@Controller
@RequestMapping("/cms/record")
public class ChangeRecordController {
	private Logger logger = LoggerFactory
			.getLogger(ChangeRecordController.class);
	@Resource
	private IChangeRecordService changeRecordService;

	@RequestMapping({ "/view/page" })
	public ModelAndView notificationListPage() {
		ModelAndView mav = new ModelAndView("changeRecord/record_list");
		return mav;
	}

	@RequestMapping({ "/view" })
	@ResponseBody
	public Object find(String customerName, String mobile, String beginDate,
			String endDate, int page, int rows) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("index", page);
		paramMap.put("size", rows);
		paramMap.put("limit", "limit");
		paramMap.put("customerName", customerName);
		paramMap.put("mobile", mobile);
		if (StringUtil.isNotEmpty(beginDate)) {
			paramMap.put("beginDate", com.wcfsy.wechat.wx.util.DateUtil
					.StringToDate(beginDate, DateStyle.YYYY_MM_DD_HH_MM_SS));
		}
		if (StringUtil.isNotEmpty(endDate)) {
			paramMap.put("endDate", com.wcfsy.wechat.wx.util.DateUtil
					.StringToDate(endDate, DateStyle.YYYY_MM_DD_HH_MM_SS));
		}
		return changeRecordService
				.queryChangeRecordByPage(paramMap, page, rows);
	}

	@RequestMapping("/detail/page")
	public ModelAndView getRecordDetail(int id) {
		ModelAndView mav = new ModelAndView("changeRecord/detail");
		ChangeRecordInfo info = changeRecordService.getChangeRecordById(id);
		mav.addObject("data", info);
		return mav;
	}

	/**
	 * 到处excel 表格
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/changeRecord/getChangeRecordExcel")
	public ModelAndView getChangeRecordExcel(String customerName,
			String mobile, String beginDate, String endDate, ModelMap modelMap) {
		Map<String, Object> paramMap = getParamMap(customerName, mobile,
				beginDate, endDate);
		IPage<ChangeRecordInfo> page = changeRecordService
				.queryChangeRecordByPage(paramMap, 1, 5000);
		if (page != null) {
			return outExcel(page.getData(), modelMap);
		}
		return null;
	}

	private Map<String, Object> getParamMap(String customerName, String mobile,
			String beginDate, String endDate) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("customerName", customerName);
		paramMap.put("mobile", mobile);
		paramMap.put("index", 1);
		paramMap.put("size", 5000);
		paramMap.put("limit", "limit");
		if (StringUtil.isNotEmpty(beginDate)) {
			paramMap.put("beginDate", com.wcfsy.wechat.wx.util.DateUtil
					.StringToDate(beginDate, DateStyle.YYYY_MM_DD_HH_MM_SS));
		}
		if (StringUtil.isNotEmpty(endDate)) {
			paramMap.put("endDate", com.wcfsy.wechat.wx.util.DateUtil
					.StringToDate(endDate, DateStyle.YYYY_MM_DD_HH_MM_SS));
		}
		return paramMap;
	}

	private ModelAndView outExcel(List<ChangeRecordInfo> wechats,
			ModelMap modelMap) {
		if (wechats.isEmpty() && wechats.size() < 0) {
			logger.info("获取的所有兑奖记录 is null ");
			return null;
		}
		Map<String, String> headerMap = new LinkedHashMap<String, String>();
		headerMap.put("changeDateStr", "兑奖日期");
		headerMap.put("changeTimeStr", "兑换时间");
		headerMap.put("customerName", "兑换人姓名");
		headerMap.put("prizeName", "奖品名称");
		headerMap.put("address", "联系地址");
		headerMap.put("nickname", "微信昵称");
		headerMap.put("openid", "微信ID");
		String dateStr = DateUtil.formatDate(new Date(), "yyyyMMddHHMMSS");
		String fileName = dateStr + "-兑奖记录详情";
		ExcelView excelView = new ExcelView(wechats, headerMap, fileName);
		logger.info("导出结束");
		return new ModelAndView(excelView, modelMap);
	}

	private String[] head_tiltes = { "兑奖日期", "兑换时间", "兑换人姓名", "奖品名称", "联系地址",
			"微信昵称", "微信ID" };
	private int[] column_width = { 20, 20, 20, 20, 50, 20, 30 };

	@RequestMapping({ "/changeRecord/getChangeRecordExcelWrite" })
	@ResponseBody
	public void export(HttpServletRequest request,
			HttpServletResponse response, String customerName, String mobile,
			String beginDate, String endDate) {
		try {
			Map<String, Object> paramMap = getParamMap(customerName, mobile,
					beginDate, endDate);
			IPage<ChangeRecordInfo> page = changeRecordService
					.queryChangeRecordByPage(paramMap, 1, 5000);
			String fileName = "changeRecord_"
					+ com.wcfsy.wechat.wx.util.DateUtil.DateToString(new Date(),
							DateStyle.YYYYMMDDHHMMSS) + ".xls";
			int index = 0;// 条数坐标
			response.setContentType("application/msexcel;charset=UTF-8");
			response.addHeader("Content-Disposition", "attachment;filename=\""
					+ fileName + "\"");
			OutputStream os = response.getOutputStream();
			WritableWorkbook workbook = Workbook.createWorkbook(os);
			WritableSheet sheet = workbook.createSheet("兑奖记录_1", 1);
			sheet.setRowView(0, 300); // 设置行的高度
			for (int windex = 0; windex < column_width.length; windex++) {
				sheet.setColumnView(windex, column_width[windex]); // 设置列的宽度
			}
			for (int title = 0; title < head_tiltes.length; title++) {
				sheet.addCell(new Label(title, 0, head_tiltes[title], ExcelUtil
						.getHeaderCellStyle()));
			}
			List<ChangeRecordInfo> registerDetaillist = page.getData();
			for (int j = 0; j < registerDetaillist.size(); j++) {
				ChangeRecordInfo vo1 = registerDetaillist.get(j);
				sheet.addCell(new Label(0, index + 1, vo1.getChangeDateStr()));
				sheet.addCell(new Label(1, index + 1, vo1.getChangeTimeStr()));
				sheet.addCell(new Label(2, index + 1, vo1.getCustomerName()));
				sheet.addCell(new Label(3, index + 1, vo1.getPrizeName()));
				sheet.addCell(new Label(4, index + 1, vo1.getAddress()));
				sheet.addCell(new Label(5, index + 1, vo1.getNickname()));
				sheet.addCell(new Label(6, index + 1, vo1.getOpenid()));
				index++;
			}
			os.flush();
			workbook.write();
			workbook.close();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
